package com.cloud.config;

import com.alibaba.fastjson.JSONObject;
import com.cloud.util.CookieUtil;
import com.cloud.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        log.info("请求调用前 请求路径" + url);
        String cookie = null;
        JSONObject result = new JSONObject();
        result.put("code",9);
        result.put("msg","用户验证超时，请重新登录");
        result.put("data","null");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        if(url.startsWith("/error")){
            result.put("msg","路径不存在");
            response.getWriter().println(result);
            return false;
        }
        if(url.startsWith("/admin/")){
            cookie = CookieUtil.getCookieValue(request,"DSG_ADMIN",true);
            if(StringUtils.hasLength(cookie)){
                try{
                    //Object o = redisUtil.get(cookie);
                    //log.info("管理员 "+o);
                    //JSONObject admin = JSONObject.parseObject(o.toString());
                    return true;
                }catch (NullPointerException e){
                    log.error(e.getMessage());
                    result.put("msg","管理员验证超时，请重新登录");
                    response.getWriter().println(result);
                    return false;
                }
            }
        }
        cookie = CookieUtil.getCookieValue(request,"DSG_USER",true);
        if(StringUtils.hasLength(cookie)){
            log.info("用户验证通过");
            return true;
        }
        log.error("用户验证失败");
        response.getWriter().println(result);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //log.info("请求调用中");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //log.info("请求调用后");
    }
}
